package fhfl.mobapp.belastungstest.mobapp_belastungstest;

import android.app.Activity;
import android.content.Context;
import android.widget.TextView;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.view.View;
import android.widget.Toast;

/**
 * Created by ViceBrot on 08.06.2014.
 */
public class SendUDPThread extends Thread
{
    private InetAddress serverIP = null;
    private int port;
    private ContentFactory ctx = null;
    private Boolean isRunning;
    private Activity activity;

    /**
     * Contructor so set the Socket parameters
     * @param serverIP
     * @param port
     */
    public SendUDPThread(String serverIP, int port, int pSize, Activity activity) throws IOException
    {
        this.serverIP = InetAddress.getByName(serverIP);
        this.port = port;
        this.ctx = new ContentFactory(pSize);
        this.isRunning = false;
        this.activity = activity;
    }

    /**
     * Thread main which is called at Thread.start()
     */
    public void run()
    {
        this.isRunning = true;

        try
        {
            DatagramSocket socket = new DatagramSocket();

            while(isRunning)
            {
                //create the context
                byte[] buffer = ctx.setPackage();

                /*final String debugString = "PacketLength: " + buffer.length + "\nPacketInhalt: " + buffer.toString();

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, debugString.toString(), Toast.LENGTH_SHORT).show();
                    }
                });*/

                socket.send(new DatagramPacket(buffer, buffer.length, serverIP, port));

                Thread.sleep(1000);
            }

            socket.close();
        }
        catch(Exception e)
        {

        }
    }

    public void finish()
    {
        this.isRunning = false;
    }

    public Boolean getIsRunning()
    {
        return this.isRunning;
    }

    public void setPacketSize(int newPacketSize)
    {
        ctx.setNewPacketSize(newPacketSize);
    }

}
